package com.yonyou.crm.sys.modules.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.modules.entity.FieldVO;
import com.yonyou.crm.sys.modules.entity.ModuleVO;
import com.yonyou.crm.sys.modules.rmitf.IFieldRmService;
import com.yonyou.crm.sys.modules.rmitf.IModuleRmService;

@RestController
@RequestMapping(value = "/sys")
public class FieldCtrl {
	
	@Autowired
	private IFieldRmService service;
    @Autowired
    private IModuleRmService moduleService;

    /**
	 * 字段列表
	 * @param objId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{objId}/fields", method = RequestMethod.GET)
	public Object getFieldList( @PathVariable("objId") Long objId, HttpServletResponse response){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<FieldVO> fieldList = service.getFieldList(objId);

		// 处理主对象
		ModuleVO mainModuleVO = moduleService.getModule(objId);
		Map<String, Object> mainModule = moduleVOToMap(mainModuleVO);	
		List<Map<String, Object>> fieldMapList = assembleFieldMapList(fieldList);
		mainModule.put("fields", fieldMapList);
		resultMap.put("mainModule", mainModule);
		if (mainModuleVO.getItem() != null) {
			ModuleVO itemModuleVO = moduleService.getModule(mainModuleVO.getItem().getId());
			Map<String, Object> itemModule = moduleVOToMap(itemModuleVO);
			List<FieldVO> itemFieldList = service.getFieldList(itemModuleVO.getId());
			List<Map<String, Object>> itemFieldMapList = assembleFieldMapList(itemFieldList);
			itemModule.put("fields", itemFieldMapList);
			resultMap.put("itemModule", itemModule);
		} else {
			resultMap.put("itemModule", null);
		}

		JSONObject result = new JSONObject();
		result.put("data", resultMap);
		return ResponseUtil.getObject(result);
	}

	/**
	 * 新增字段
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{objId}/fields", method = RequestMethod.POST)
	public Object addField(@PathVariable("objId") Long objId,
			HttpServletRequest request, HttpServletResponse response){
		FieldVO field = RequestUtil.getVO(request, FieldVO.class);
		field.setObjId(objId);
		field.setIsCustom(1);
		field = service.addField(field);
		JSONObject result = new JSONObject();
		Map<String, Object> resultMap = fieldVOToMap(field);
		result.put("data", resultMap);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 修改字段
	 * @param fullname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fields/{fullname:.+}", method = RequestMethod.PUT)
	public Object updateField(@PathVariable("fullname") String fullname,
			HttpServletRequest request, HttpServletResponse response){
		FieldVO field = RequestUtil.getVO(request, FieldVO.class);
		field.setFullname(fullname);
		field = service.updateField(field);
		JSONObject result = new JSONObject();
		Map<String, Object> resultMap = fieldVOToMap(field);
		result.put("data", resultMap);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 字段详情（前端暂时不用了）
	 * @param fullname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fields/{fullname:.+}", method = RequestMethod.GET)
	public Object getField(@PathVariable("fullname") String fullname,
			HttpServletRequest request, HttpServletResponse response){
		
		FieldVO field  = service.getField(fullname);	
		Map<String, Object> resultMap = fieldVOToMap(field);
		JSONObject result = new JSONObject();
		result.put("data", resultMap);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 字段删除
	 * @param fullname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fields/{fullname:.+}", method = RequestMethod.DELETE)
	public Object deleteField(@PathVariable("fullname") String fullname,
			HttpServletRequest request, HttpServletResponse response){	
		 service.deleteField(fullname);	
		JSONObject result = new JSONObject();
		return ResponseUtil.getObject(result);
	}
	
	private List<Map<String, Object>>  assembleFieldMapList(List<FieldVO>fieldList) {
		List<Map<String, Object>> fieldMapList = new ArrayList<Map<String,Object>>();
		for (FieldVO field: fieldList) {
			if (field.getIsDisplayable() == 0 || isCompositeField(field.getApiName())) {
				continue;
			}
			Map<String, Object> resultMap = fieldVOToMap(field);
			fieldMapList.add(resultMap);
		}
		return fieldMapList;
	}
	
	private Map<String, Object>moduleVOToMap(ModuleVO module) {
		Map<String, Object> moduleMap = new HashMap<String, Object>();
		moduleMap.put("id", module.getId());
		moduleMap.put("name", module.getName());
		moduleMap.put("apiName", module.getApiName());
		return moduleMap;
	}
	
	private Boolean isCompositeField(String fieldName) {
		return fieldName.indexOf(".") != -1;
	}
	
	private Map<String, Object>fieldVOToMap(FieldVO field) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> oprMap = new HashMap<String, Object>();
		dataMap.put("type", field.getType());
		dataMap.put("fullname", field.getFullname());
		dataMap.put("name", field.getName());
		dataMap.put("apiName", field.getApiName());
		dataMap.put("description", field.getDescription());
		dataMap.put("isCustom", field.getIsCustom());
		dataMap.put("defaultChecked", field.getDefaultChecked());
		dataMap.put("minValue", field.getMinValue());
		dataMap.put("maxValue", field.getMaxValue());
		dataMap.put("length", field.getLength());
		dataMap.put("precision", field.getPrecision());
		dataMap.put("isRequired", field.getIsRequired());
		dataMap.put("isReadonly", field.getIsReadonly());
		if (field.getIsCustom() == 1) {
			oprMap.put("delete", 1);
		} else {
			oprMap.put("delete", 0);
		}
		oprMap.put("edit", 1);
		resultMap.put("data", dataMap);
		resultMap.put("operations", oprMap);	
		return resultMap;
	}
	
	/**
	 * 获取字段类型列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{objId}/customFieldTypes", method = RequestMethod.GET)
	public Object availableFieldTypeNum(@PathVariable("objId") Long objId,
			HttpServletRequest request, HttpServletResponse response){
		 List<Object>  rs= service.getCustomFieldTypes(objId);
		JSONObject result = new JSONObject();
		result.put("data", rs);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 档案列表信息
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "baseDocDetail", method = RequestMethod.GET)
	public Object getDocAndDetailList(HttpServletRequest request, HttpServletResponse response) 
			throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> baseDocMaps = service.getBaseDocList(param);
		return ResponseUtil.getObject(baseDocMaps);
	}
}
